#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>

void error(char* msg);

int main(int argc, char *argv[])
{
		int descriptor_cliente; 
		int port_servidor = 6211;

		struct sockaddr_in serv_addr;
		struct hostent *server;

		/*	
		* Abrimos el socket
		* */
		descriptor_cliente = socket(AF_INET, SOCK_STREAM, 0);
		if (descriptor_cliente< 0) 
			error("ERROR opening socket");
    
    
		server = gethostbyname("localhost");
		if (server == NULL) {
			fprintf(stderr,"ERROR, no such host\n");
			exit(0);
		}
    
		bzero((char *) &serv_addr, sizeof(serv_addr));
		serv_addr.sin_family = AF_INET;
		bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
		serv_addr.sin_port = htons(port_servidor);
		
		
		if (connect(descriptor_cliente,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
			error("ERROR connecting");
		
		/*
		 * Escribir y Leer
		 * */
		char buffer[256];
		int n;
			
		printf("Please enter the message: ");
		bzero(buffer, 256);
		fgets(buffer, 255, stdin);
        // n = write(sockfd, buffer, strlen(buffer));
		n = write(descriptor_cliente, buffer, strlen(buffer));
		if (n < 0) error("ERROR writing to socket");

		bzero(buffer, 256);
		// n = read(sockfd, buffer, 255);
		n = read(descriptor_cliente,buffer,255);
		if (n < 0) error("ERROR reading from socket");

		printf("%s\n", buffer);
		
		close(descriptor_cliente);
  
		return 0;
    
 }
 
 
void error(char *msg)
{
    perror(msg);
    exit(0);
}
